//
//  MYUserinfoViewModel.swift
//  NewMicroblog
//
//  Created by apple on 2016/10/25.
//  Copyright © 2016年 apple. All rights reserved.
//

import UIKit

class MYUserinfoViewModel {
    
    static let sharedModel:MYUserinfoViewModel = MYUserinfoViewModel()
    var userInfoModel: MYUserinfoModel?
    
    /// 沙盒路径
    fileprivate let filePath = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent("lijunyu.db")
    var islogin:Bool{
        return accessToken != nil
    }
    
    var accessToken:String?{
        if userInfoModel?.expires_Date?.compare(Date()) == ComparisonResult.orderedDescending {
            return userInfoModel?.access_token
        }else{
            return nil
        }
    }
    
    init() {
       userInfoModel = getUserMessage()
    }

}

// MARK: -帮助控制请求用户信息
extension MYUserinfoViewModel{
    func getMessage(code:String, finish:@escaping (Bool)->()){
        MYNetworkingTool.shareTool.oauthUserAccount(code: code, success: { (result) in
            guard let res = result as?[String:Any] else{
                finish(false)
                return
            }
            let userModel = MYUserinfoModel.yy_model(withJSON: res)
            guard let model =  userModel else{
                finish(false)
                return
            }
            self.getUserInfo(model: model, finish: finish)
            }) { (error) in
                finish(false)
                print(error)
        }
        
    }
    
    func getUserInfo(model:MYUserinfoModel, finish:@escaping (Bool)->()){
        MYNetworkingTool.shareTool.oauthUserInfo(model: model, success: { (result) in
            guard let res = result as?[String:Any] else{
                finish(false)
                return
            }
            model.screen_name = res["screen_name"] as? String
            model.avatar_large = res["avatar_large"] as? String
            self.saveUserMessage(model: model)
            finish(true)
            }) { (error) in
                finish(false)
                print(error)
        }
    }
    
    
}


// MARK: - 接档和归档方法
extension MYUserinfoViewModel{
    
   fileprivate func saveUserMessage(model:MYUserinfoModel){
        userInfoModel = model
        NSKeyedArchiver.archiveRootObject(model, toFile: filePath)
    }
    
   fileprivate func getUserMessage()->MYUserinfoModel?{
       let res = NSKeyedUnarchiver.unarchiveObject(withFile: filePath) as? MYUserinfoModel
      return res
    }
    
}
